package main.java.jin.singleton;

/**
 * double lock 的单例
 * 缺点 :
 *  instance = new Singleton()
 *  实例化一个对象 要经过以下的步骤
 *  memory = allocate();   //1：分配对象的内存空间
 *  ctorInstance(memory);  //2：初始化对象
 *  instance = memory;     //3：设置instance指向刚分配的内存地址
 *  **************通过重排序后*****************************
 *
 *  memory = allocate();   //1：分配对象的内存空间
 *  instance = memory;     //3：设置instance指向刚分配的内存地址
 *                        //注意，此时对象还没有被初始化！
 *  ctorInstance(memory);  //2：初始化对象
 *
 *
 *  $$使用volatile变量禁止指令重排序$$
 *
 */

public class DoubleLockSingleton {

    private static volatile DoubleLockSingleton singleton;

    private DoubleLockSingleton() {
    }

    public DoubleLockSingleton getSingleton() {
        if (singleton == null) {
            synchronized (DoubleLockSingleton.class) {
                if (singleton == null) {
                    singleton = new DoubleLockSingleton();
                }
            }
        }
        return singleton;

    }

}
